<template>

  <el-dialog :title="id ? '终端修改' : '终端添加'" :visible.sync="dialogVisible" width="900px" :close-on-click-modal="false">

    <el-form ref="main-form" :model="form" :rules="rules" label-width="180px" :inline="true" >

      <el-form-item label="终端名称" size="mini" prop="terName">
        <el-input placeholder="" v-model="form.terName" @keyup.enter.native="submit" clearable></el-input>
      </el-form-item>

      <el-form-item label="商户（可搜索）" size="mini" prop="mchId">
        <el-select
          v-model="form.mchId"
          filterable
          remote
          reserve-keyword
          :disabled="id != null && id != ''"
          placeholder="输入商户号或商户名称搜索商户"
          :remote-method="fetchMchOptions"
          :loading="mchLoading">
          <el-option
            v-for="item in mchOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="账户名称" size="mini" prop="accountName">
        <el-input placeholder="" v-model="form.accountName" @keyup.enter.native="submit" clearable></el-input>
      </el-form-item>

      <el-form-item label="交易币种（可多选）" size="mini" prop="mchTransCurrency">

        <div style="margin: 0 0; margin-bottom: 15px; margin-left: 180px;">
          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
        </div>

        <el-checkbox-group style="margin-left: 180px;" v-model="form.mchTransCurrency" @change="handleCheckChange">

          <el-divider content-position="left">中行币种</el-divider>
          <el-row>
            <el-col :span="6" v-for="item in currencyOptions">
              <el-checkbox :label="item.value">{{item.label}}</el-checkbox>
            </el-col>
          </el-row>

          <template v-if="otherCurrencyOptions.length > 0">
            <el-divider content-position="left">其他币种</el-divider>
            <el-row>
              <el-col :span="6" v-for="item in otherCurrencyOptions">
                <el-checkbox :label="item.value">{{item.label}}</el-checkbox>
              </el-col>
            </el-row>
          </template>

        </el-checkbox-group>

      </el-form-item>

      <el-form-item label="结算币种（单选）" size="mini" prop="settleCurrency">
        <cascader-currency v-model="form.settleCurrency"></cascader-currency>
      </el-form-item>

      <el-form-item label="银行账号" size="mini" prop="accountNo">
        <el-input placeholder="" v-model="form.accountNo" @keyup.enter.native="submit" clearable></el-input>
      </el-form-item>

      <el-form-item label="收款银行" size="mini" prop="accountBank">
        <el-input placeholder="" v-model="form.accountBank" @keyup.enter.native="submit" clearable></el-input>
      </el-form-item>

      <el-form-item label="银行号" size="mini" prop="accountBankNo">
        <el-input placeholder="" v-model="form.accountBankNo" @keyup.enter.native="submit" clearable></el-input>
      </el-form-item>

      <el-form-item label="swift" size="mini">
        <el-input placeholder="" v-model="form.swift" @keyup.enter.native="submit" clearable></el-input>
      </el-form-item>

      <el-form-item label="关联网关通道集合（单选）" size="mini" prop="channelCollectionId">
        <el-select v-model="form.channelCollectionId" filterable size="small" clearable>
          <el-option
            v-for="item in channelCollectionIdOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="交易汇率（单选）" size="mini" prop="tradeRateGroupId">
        <el-select v-model="form.tradeRateGroupId" size="small" filterable clearable>
          <el-option
            v-for="item in tradeRateGroupIdOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="结算费率（单选）" size="mini" prop="settleRateId">
        <el-select v-model="form.settleRateId" size="small" filterable clearable>
          <el-option
            v-for="item in settleRateIdOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="风控集合（单选）" size="mini" prop="riskCollectionId">
        <el-select v-model="form.riskCollectionId" size="small" filterable clearable>
          <el-option
            v-for="item in riskCollectionIdOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="可疑风控集合（单选）" size="mini" prop="suspiciousCollectionId">
        <el-select v-model="form.suspiciousCollectionId" size="small" filterable clearable>
          <el-option
            v-for="item in suspiciousCollectionIdOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="第三方风控" size="mini">
        <el-select v-model="form.thirdRiskChannel" size="small" filterable clearable>
          <el-option
            v-for="item in thirdRiskChannelOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="白名单（单选）" size="mini">
        <el-select v-model="form.whiteTextId" size="small" filterable clearable>
          <el-option
            v-for="item in whiteTextIdOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="备注" size="mini">
        <el-input placeholder="" v-model="form.remark" @keyup.enter.native="submit" clearable></el-input>
      </el-form-item>

      <el-form-item label="产品" size="mini" prop="sysProductId">
        <el-select v-model="form.sysProductId" size="small" filterable clearable>
          <el-option
            v-for="item in sysProductOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="品牌" size="mini" prop="sysBrandId">
        <el-select v-model="form.sysBrandId" size="small" clearable filterable>
          <el-option
            v-for="item in sysBrandOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="状态" size="mini">
        <el-select v-model="form.status" size="small" clearable filterable>
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-popover
        v-if="id != null"
        placement="top"
        width="160"
        v-model="popDeleteVisible">
        <p>确定删除吗？</p>
        <div style="text-align: right; margin: 0">
          <el-button size="mini" type="default" @click="popDeleteVisible = false">取消</el-button>
          <el-button type="danger" size="mini" @click="submitDel">确定</el-button>
        </div>
        <el-button type="danger" slot="reference"  size="small" style="float: left;" :loading="loading">删 除</el-button>
      </el-popover>

      <el-button @click="close" size="small">取 消</el-button>
      <el-button type="primary" @click="submit" size="small" :loading="loading">提 交</el-button>
    </div>

  </el-dialog>
</template>

<script>

import ApiMain from '@/api/mch.ter';
import RateSettleApiMain from '@/api/mch.rateSettle';
import ProductApiMain from '@/api/product.info';
import RiskCollectionApiMain from '@/api/risk.collection';
import WhiteTextApiMain from '@/api/risk.whiteText';
import RateGroupApiMain from '@/api/exchangeRate.rateGroup';
import BrandProductApiMain from '@/api/platform.brandProduct';
import MchApiMain from '@/api/mch.info';
import ApiRateBoc from '@/api/exchangeRate.rateBoc';
import ApiRateOther from '@/api/exchangeRate.rateOther'
import { thirdRiskChannelOptions, defaultTransCurrencyOptions } from '@/const/constant';

import CascaderCurrency from "@/views/exchangeRate/rateCustomized/components/cascader-currency";

export default {
  mixins: [
  ],
  props: [
  ],
  components: {
    CascaderCurrency,
  },
  data () {
    return {

      dialogVisible: false,
      popDeleteVisible: false,
      loading: false,
      mchLoading: false,

      isIndeterminate: true,
      checkAll: false,

      form: {
        terName: '',
        mchId : '',
        mchTransCurrency : defaultTransCurrencyOptions,
        settleCurrency: '',
        accountName : '',
        accountNo: '',
        accountBank : '',
        accountBankNo : '',
        accountCountry : '',
        accountState: '',
        accountCity : '',
        channelCollectionId : '',
        settleRateId : '',
        tradeRateGroupId: '',
        suspiciousCollectionId : '',
        riskCollectionId : '',
        whiteTextId: '',
        thirdRiskChannel : 0,
        sysProductId: '',
        sysBrandId: '',
        swift : '',
        referer: '',
        status: 1,
        remark : '',
      },

      rules: {
        terName: [
          { required: true, message: '请输入终端名称', trigger: 'blur' },
        ],
        mchId: [
          { required: true, message: '请选择商户', trigger: 'blur' },
        ],
        mchTransCurrency: [
          { required: true, message: '请选择交易币种', trigger: 'blur' },
        ],
        accountName: [
          { required: true, message: '请输入终端账户名称', trigger: 'blur' },
        ],
        settleCurrency: [
          { required: true, message: '请选择结算币种', trigger: 'blur' },
        ],
        accountNo: [
          { required: true, message: '请输入银行卡名称', trigger: 'blur' },
        ],
        accountBank: [
          { required: true, message: '请输入收款银行', trigger: 'blur' },
        ],
        accountBankNo: [
          { required: true, message: '请输入收款银行号', trigger: 'blur' },
        ],
        channelCollectionId: [
          { required: true, message: '请选择网关通道集合', trigger: 'blur' },
        ],
        settleRateId: [
          { required: true, message: '请选择结算费率', trigger: 'blur' },
        ],
        tradeRateGroupId: [
          { required: true, message: '请选择交易费率', trigger: 'blur' },
        ],
        suspiciousCollectionId: [
          { required: true, message: '请选择可疑风控', trigger: 'blur' },
        ],
        riskCollectionId: [
          { required: true, message: '请选择风控', trigger: 'blur' },
        ],
        sysBrandId: [
          { required: true, message: '请选择产品', trigger: 'blur' },
        ],
        sysProductId: [
          { required: true, message: '请选择品牌', trigger: 'blur' },
        ],
      },

      id  : null,
      data: null,

      mchOptions: [],
      channelCollectionIdOptions: [],
      settleRateIdOptions: [],
      tradeRateGroupIdOptions: [],
      suspiciousCollectionIdOptions: [],
      riskCollectionIdOptions: [],
      whiteTextIdOptions: [],
      currencyOptions: [],
      otherCurrencyList: [],
      sysProductOptions: [],
      sysBrandOptions: [],
      thirdRiskChannelOptions: thirdRiskChannelOptions,
      statusOptions: [
        {label: '正常', value: 1},
        {label: '关闭', value: 0},
      ]
    }
  },
  computed: {
      otherCurrencyOptions () {

        var options = [];

        this.otherCurrencyList.forEach(item => options.push({
          value: item.code,
          label: `${item.code}-${item.name}`,
        }));

        return options;
      },
  },
  mounted () {
    this.fetchMchOptions()
    this.fetchRateSettleOptions()
    this.fetchProductOptions()
    this.fetchRiskCollectionOptions()
    this.fetchSuspiciousCollectionIdOptions()
    this.fetchWhiteTextOptions()
    this.fetchRateGroupOptions()
    this.fetchCurrencyOptions()
    this.fetchOtherCurrencyList()
    this.fetchSysBrandOptions()
    this.fetchSysProductOptions()
  },

  methods: {

    handleCheckAllChange(val) {

      if (val) {
        this.form.mchTransCurrency = this.currencyOptions.map(item => item.value).concat(this.otherCurrencyOptions.map(item => item.value));
      }
      else {
        this.form.mchTransCurrency = [];
      }

      this.isIndeterminate = false;
    },

    handleCheckChange(value) {

      let checkedCount = value.length;
      this.checkAll = checkedCount === this.currencyOptions.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.currencyOptions.length;
    },

    show (id = null) {

      this.id = id;

      if (this.id) {
        this.fetchData();
      }
      else {
        this.reset();
        this.fetchMchOptions();
      }

      this.dialogVisible = true;
    },

    close () {
      this.dialogVisible = false;
      this.$emit('dialog-close');
    },

    reset () {
      this.form = {
        terName: '',
        mchId : '',
        mchTransCurrency : defaultTransCurrencyOptions,
        settleCurrency: '',
        accountName : '',
        accountNo: '',
        accountBank : '',
        accountBankNo : '',
        accountCountry : '',
        accountState: '',
        accountCity : '',
        channelCollectionId : '',
        settleRateId : '',
        tradeRateGroupId: '',
        suspiciousCollectionId : '',
        riskCollectionId : '',
        whiteTextId: '',
        thirdRiskChannel : 0,
        sysProductId: '',
        sysBrandId: '',
        swift : '',
        referer: '',
        status: 1,
        remark : '',
      };
    },

    async fetchOtherCurrencyList () {
      var re = await ApiRateOther.list({
          page: 1, limit: 1e3,
          search: {
            status: 1,
          },
        });
      this.otherCurrencyList = re.list;
    },

    async fetchCurrencyOptions () {
      this.currencyOptions = await ApiRateBoc.getCurrencyOptions();
    },

    fetchMchOptions (search, id) {
      this.mchLoading = true
      MchApiMain.option({ search: search, id: id ? id : '' }).then(re => {
        this.mchOptions = re
        this.mchLoading = false
      })
    },

    fetchProductOptions () {
      ProductApiMain.option().then(re => {
        this.channelCollectionIdOptions = re;
      })
    },

    fetchRateSettleOptions () {
      RateSettleApiMain.option().then(re => {
        this.settleRateIdOptions = re;
      })
    },

    fetchRiskCollectionOptions () {
      RiskCollectionApiMain.option({ type: 2 }).then(re => {
        this.riskCollectionIdOptions = re;
      })
    },

    fetchSuspiciousCollectionIdOptions () {
      RiskCollectionApiMain.option({ type: 4 }).then(re => {
        this.suspiciousCollectionIdOptions = re;
      })
    },

    fetchWhiteTextOptions () {
      WhiteTextApiMain.option().then(re => {
        this.whiteTextIdOptions = re;
      })
    },

    fetchRateGroupOptions () {
      RateGroupApiMain.option().then(re => {
        this.tradeRateGroupIdOptions = re;
      })
    },

    fetchSysBrandOptions () {
      BrandProductApiMain.option({ type: 2 }).then(re => {
        this.sysBrandOptions = re;
      })
    },

    fetchSysProductOptions () {
      BrandProductApiMain.option({ type: 1 }).then(re => {
        this.sysProductOptions = re;
      })
    },

    fetchData () {

      ApiMain.info({id: this.id})
      .then(re => {
        this.data = re;
      })
      .catch(() => {
        this.data = null;
      })
      .finally(() => {
        this.renderData();
        this.fetchMchOptions('', this.data.mchId)
      });
    },

    renderData () {
      this.form.terName = this.data.terName
      this.form.mchId = this.data.mchId
      this.form.mchTransCurrency = this.data.mchTransCurrency
      this.form.settleCurrency = this.data.settleCurrency
      this.form.accountName = this.data.accountName
      this.form.accountNo = this.data.accountNo
      this.form.accountBank = this.data.accountBank
      this.form.accountBankNo = this.data.accountBankNo
      this.form.accountCountry = this.data.accountCountry
      this.form.accountState = this.data.accountState
      this.form.accountCity = this.data.accountCity
      this.form.channelCollectionId = this.data.channelCollectionId
      this.form.settleRateId = this.data.settleRateId
      this.form.tradeRateGroupId = this.data.tradeRateGroupId
      this.form.suspiciousCollectionId = this.data.suspiciousCollectionId
      this.form.riskCollectionId = this.data.riskCollectionId
      this.form.whiteTextId = this.data.whiteTextId
      this.form.thirdRiskChannel = this.data.thirdRiskChannel
      this.form.sysProductId = this.data.sysProductId
      this.form.sysBrandId = this.data.sysBrandId
      this.form.swift = this.data.swift
      this.form.referer = this.data.referer
      this.form.status = this.data.status
      this.form.remark = this.data.remark
    },

    verifyForm () {
      var bool = true;
      this.$refs['main-form'].validate((valid) => bool = valid);
      return bool;
    },

    async submit () {

      if (! this.verifyForm()) return false;

      this.loading = true;

      try {
        if (this.id) {
          await this.submitSet();
        }
        else {
          await this.submitAdd();
        }
      } finally {
        this.loading = false;
      }
    },

    async submitDel() {

      this.popDeleteVisible = false;
      this.loading = true;

      await ApiMain.del({id: this.id});

      this.loading = false;
      this.close();
      this.$message({message: '删除成功', type: 'success'});
    },

    buildQuery () {

      var req = Object.copy(this.form);
      req.mchTransCurrency = req.mchTransCurrency.join(",");

      if (Array.isArray(req.settleCurrency)) {
        req.settleCurrency = req.settleCurrency[1];
      }

      return req;
    },

    async submitSet () {

      let form = this.buildQuery();
      form.id = this.id;

      await ApiMain.set(form);
      this.$message({message: '修改成功', type: 'success'});
      this.close();

    },

    async submitAdd () {

      let form = this.buildQuery();

      await ApiMain.add(form);
      this.$message({message: '添加成功', type: 'success'});
      this.close();
    },
  }
}
</script>

<style>

</style>
